#include <QtWidgets>
#include <QAxObject>
#include <QNetworkReply>
#include <QNetworkRequest>

#include "global.h"

QString gloPath;
QString stoPath;
QString datFile;
QString logFile;
QString configFile;
QString settingFile;
QString cmdFile;
QString machineCode;
QString appkey;
QString appsecret;
QString placeCode;
QNetworkAccessManager nam;


QString gloUrl = "http://facereco.eshanren.com/";

void writeFile(QString *fileName, QString context) {
	QFile file(*fileName);
	if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) {
		QTextStream out(&file);
		out.seek(file.size());
		out << context;

		file.close();
	}
}
QString readFile(QString *fileName, int startPos, int length) {
	QString info = QObject::tr("");
	QFile file(*fileName);
	if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QString str(file.readLine());

		info = str.mid(startPos, length);
	}
	return info;
}


void writeLog(QString context) {
	writeLog(context, false);
}
void writeLog(QString context, bool ereaseTime) {
	if (!ereaseTime) {
		writeFile(&logFile, getCurrentTime() + " ");
	}
	writeFile(&logFile, context + "\n");
}


void writeSetting(QString *fileName, QString group, QString key, QString val) {
	QSettings settings(*fileName, QSettings::IniFormat);
	settings.beginGroup(group);
	settings.setValue(key, val);
}
QString readSetting(QString *fileName, QString group, QString key) {
	QSettings settings(*fileName, QSettings::IniFormat);

	return settings.value(group + "/" + key).toString();
}


QString getMD5(QString input) {
	QString md5;
	QByteArray bb;
	bb = QCryptographicHash::hash(input.toUtf8(), QCryptographicHash::Md5);
	md5.append(bb.toHex());

	return md5;
}

QString getWMIHWInfo() {
	QString hwInfo=QObject::tr("");

	QStringList sqlCmd;
	sqlCmd.clear();

	// sqlCmd<<QObject::tr("SELECT MACAddress FROM Win32_NetworkAdapter WHERE (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%'))");
	// sqlCmd<<QObject::tr("SELECT PNPDeviceID FROM Win32_DiskDrive WHERE( PNPDeviceID IS NOT NULL) AND (MediaType LIKE 'Fixed%')");
	sqlCmd<<QObject::tr("SELECT SerialNumber FROM Win32_BaseBoard WHERE (SerialNumber IS NOT NULL)");
	sqlCmd<<QObject::tr("SELECT ProcessorId FROM Win32_Processor WHERE (ProcessorId IS NOT NULL)");
	// sqlCmd<<QObject::tr("SELECT SerialNumber FROM Win32_BIOS WHERE (SerialNumber IS NOT NULL)");
	// sqlCmd<<QObject::tr("SELECT Product FROM Win32_BaseBoard WHERE (Product IS NOT NULL)");

	QStringList columnName;
	columnName.clear();
	// columnName<<QObject::tr("MACAddress");
	// columnName<<QObject::tr("PNPDeviceID");
	columnName<<QObject::tr("SerialNumber");
	columnName<<QObject::tr("ProcessorId");
	// columnName<<QObject::tr("SerialNumber");	
	// columnName<<QObject::tr("Product");


	QAxObject *objIWbemLocator = new QAxObject("WbemScripting.SWbemLocator");
	QAxObject *objWMIService =objIWbemLocator->querySubObject("ConnectServer(QString&,QString&)",QString("."),QString("root\\cimv2"));
	QString query=QObject::tr("");
	for (int j=0; j<sqlCmd.size(); j++) {
		query=sqlCmd.at(j);

		QAxObject *objInterList = objWMIService->querySubObject("ExecQuery(QString&))", query);
		QAxObject *enum1 = objInterList->querySubObject("_NewEnum");
		//需要 include windows.h
		IEnumVARIANT* enumInterface = 0;
		enum1->queryInterface(IID_IEnumVARIANT, (void**)&enumInterface);
		enumInterface->Reset();
		for (int i = 0; i < objInterList->dynamicCall("Count").toInt(); i++) {
			VARIANT *theItem = (VARIANT*)malloc(sizeof(VARIANT));
			if (enumInterface->Next(1,theItem,NULL) != S_FALSE){
				QAxObject *item = new QAxObject((IUnknown *)theItem->punkVal);
				if(item){
					QByteArray ba = columnName.at(j).toUtf8();
					hwInfo+= item->dynamicCall(ba.data()).toString() + ";";
				}
			}
		}
	}

	return hwInfo;
}

QString getCurrentTime() {
	QDateTime time = QDateTime::currentDateTime();
	return time.toString("yyyy-MM-dd hh:mm:ss");
}

bool copyDirectoryFiles(const QString &fromDir, const QString &toDir) {
	QDir sourceDir(fromDir);
	QDir targetDir(toDir);

	QFileInfoList fileInfoList = sourceDir.entryInfoList();
	foreach(QFileInfo fileInfo, fileInfoList) {
		if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
			continue;

		if(fileInfo.isDir()){
			QString dirPath = targetDir.filePath(fileInfo.fileName());
			QDir dir(dirPath);
			if (!dir.exists())
				dir.mkdir(dirPath);

			if(!copyDirectoryFiles(fileInfo.filePath(), targetDir.filePath(fileInfo.fileName())))
				return false;  
		} else {
			if(targetDir.exists(fileInfo.fileName())){
				targetDir.remove(fileInfo.fileName());
			}

			if(!QFile::copy(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName()))) {  
				return false;
			}
		}
	}
	return true;
}
